<?php

namespace App\Console\Commands\Poi;

use App\Http\Middleware\OpenShop\WangGuiCityByPower;
use App\Models\Common\CityTerritorialBoundaryModel;
use App\Models\OpenShop\Wanggui\LianJiaCommunityListModel;
use App\Models\Wanggui\BusinessAoiModel;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class CommunityList extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'poi:community-list';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '获得小区数据';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * @throws GuzzleException
     */
    public function handle()
    {
        ini_set('memory_limit', '1024M');


        BusinessAoiModel::query()
            ->where('province', '北京市')
            ->where('level', 'bizcircle')
            ->where('id', '>', '1368')
            ->each(function (BusinessAoiModel $businessAoiModel) {
                $range             = self::getMaxMinLngLat(json_decode($businessAoiModel->boundary, true));
                $communityList     = self::getCommunityList($businessAoiModel->cityCode, 'community', $range);
                $tempCommunityData = [];

                foreach (($communityList['bubbleList'] ?? []) as $community) {
                    try {
                        $border = collect(explode(';', $community['border']))->map(function ($item) {
                            $arr = explode(',', $item);
                            return [
                                'lng' => $arr[0],
                                'lat' => $arr[1]
                            ];
                        });
                    } catch (\Exception $exception) {
                        $border = [];
                    }

                    $tempCommunityData[] = [
                        'province'    => $businessAoiModel->province,
                        'city'        => $businessAoiModel->city,
                        'district'    => $businessAoiModel->district,
                        'cityCode'    => $businessAoiModel->cityCode,
                        'level'       => 'community',
                        'fullSpell'   => $community['fullSpell'],
                        'desc'        => $community['fullSpell'],
                        'count'       => (int)$community['count'],
                        'countStr'    => $community['countStr'],
                        'price'       => (float)$community['price'],
                        'priceStr'    => $community['priceStr'],
                        'priceUnit'   => $community['priceUnit'],
                        'border'      => json_encode($border),
                        'bubbleDesc'  => $community['bubbleDesc'],
                        'icon'        => $community['icon'],
                        'entityId'    => $community['entityId'],
                        'entityType'  => $community['entityType'],
                        'communityId' => $community['id'],
                        'name'        => $community['name'],
                        'lng'         => $community['longitude'],
                        'lat'         => $community['latitude'],
                        'imageType'   => $community['imageType'],
                        'selected'    => $community['selected'],
                        'createdAt'   => time(),
                        'updatedAt'   => time(),
                    ];
                }
                $this->info('共有' . count($tempCommunityData) . '条记录');

                $arr = array_chunk($tempCommunityData, 50);

                foreach ($arr as $item) {
                    LianJiaCommunityListModel::query()->insert($item);
                }
                $this->info($businessAoiModel->name . 'community级别的小区添加完成');

            });
    }


    /**
     * 获得小区列表
     * @param int $cityCode
     * @param string $groupType
     * @param array $boundary
     * @return array
     */
    public static function getCommunityList(int $cityCode, string $groupType, array $boundary): array
    {
        return Http::withOptions([
            'http_errors' => false,
        ])->withHeaders([
            'accept' => 'application/json, text/plain, */*',
        ])->get(
            'https://map.ke.com/proxyApi/i.c-pc-webapi.ke.com/map/bubblelist', array_merge([
                'cityId'     => $cityCode,
                'groupType'  => $groupType,
                'dataSource' => 'ESF',
                'condition'  => '',
                'id'         => '',
            ], $boundary)
        )->json('data');
    }

    // 获取最大的最小的经纬度
    public static function getMaxMinLngLat(array $data): array
    {
        // 初始化最大最小经纬度为第一个元素的值
        $minLat = $maxLat = $data[0]['lat'];
        $minLng = $maxLng = $data[0]['lng'];

        // 遍历数组查找最大最小经纬度
        foreach ($data as $coordinate) {
            $lat = $coordinate['lat'];
            $lng = $coordinate['lng'];

            if ($lat < $minLat) {
                $minLat = $lat;
            }

            if ($lat > $maxLat) {
                $maxLat = $lat;
            }

            if ($lng < $minLng) {
                $minLng = $lng;
            }

            if ($lng > $maxLng) {
                $maxLng = $lng;
            }
        }

        return [
            'maxLatitude'  => $maxLat,
            'minLatitude'  => $minLat,
            'maxLongitude' => $maxLng,
            'minLongitude' => $minLng,
        ];
    }


}
